<template>
  <table class="search-box">
    <tr class="vat">
      <td class="search">
        <el-button type="primary" @click="showAddDialog"> 新增 </el-button>
        <el-input
          placeholder="名称"
          clearable
          class="keyword ml10"
          v-model="searchKeyword"
          @input="inputSearch"
        >
          <template #prepend>关键字</template>
        </el-input>
        <!-- <el-button type="primary" class="ml10" @click="userSearch">
          搜索
        </el-button>
        <el-button @click="clearSearch">清空</el-button> -->
        <el-button type="primary" @click="reload"> 刷新 </el-button>
      </td>
      <!-- <td class="tar">

      </td> -->
    </tr>
  </table>
  <div class="demo-pagination-block">
    <div class="demonstration">
      <el-table v-loading="loading" :data="paginatedItems" style="width: 100%">
        <el-table-column label="最近登录" prop="logintime" />
        <el-table-column label="登录IP" prop="loginip" />
        <el-table-column label="姓名" prop="name" />
        <el-table-column label="账号" prop="username" />
        <el-table-column label="手机号" prop="phone" />
        <el-table-column label="权限" prop="role" />
        <!-- <el-table-column label="密码" prop="password" /> -->
        <el-table-column align="right">
          <template #default="scope">
            <el-button size="small" @click="showEditDialog(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="showDeleteDialog(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[15, 30, 60, 120, 240]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalItems"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
  <el-dialog v-model="addDialogVisible" title="新增信息" width="20rem">
    <el-form :model="addFormData">
      <el-form-item label="姓名" label-width="auto">
        <el-input
          v-model="addFormData.name"
          autocomplete="off"
          placeholder="请输入姓名"
        ></el-input>
      </el-form-item>
      <el-form-item label="账号" label-width="auto">
        <el-input
          v-model="addFormData.username"
          autocomplete="off"
          placeholder="请输入账号"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" label-width="auto">
        <el-input
          v-model="addFormData.password"
          autocomplete="off"
          placeholder="请输入密码"
          type="password"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号" label-width="auto">
        <el-input
          v-model="addFormData.phone"
          autocomplete="off"
          placeholder="请输入手机号"
        ></el-input>
      </el-form-item>
      <el-form-item label="权限" label-width="auto">
        <el-select v-model="addFormData.role" placeholder="请选择角色">
          <el-option label="用户" value="user"></el-option>
          <el-option label="管理员" value="admin"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="addDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitAddForm">确定</el-button>
    </template>
  </el-dialog>
  <el-dialog v-model="editDialogVisible" title="编辑信息" width="20rem">
    <el-form :model="editFormData">
      <el-form-item label="姓名" label-width="auto">
        <el-input v-model="editFormData.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="账号" label-width="auto">
        <el-input v-model="editFormData.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" label-width="auto">
        <el-input
          v-model="editFormData.password"
          autocomplete="off"
          placeholder="请输入新密码"
          type="password"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号" label-width="auto">
        <el-input v-model="editFormData.phone" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="权限" label-width="auto">
        <el-select v-model="editFormData.role" placeholder="请选择角色">
          <el-option label="用户" value="user"></el-option>
          <el-option label="管理员" value="admin"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitEditForm">确定</el-button>
    </template>
  </el-dialog>
  <el-dialog v-model="deleteDialogVisible" title="确认删除" width="30%">
    <p>确认要删除这条数据吗？</p>
    <template #footer>
      <el-button @click="deleteDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmDelete">确定</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, onMounted, computed } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import _ from "lodash";

const currentPage = ref(1);
const pageSize = ref(15);
const small = ref(true);
const background = ref(true);
const disabled = ref(false);
const handleSizeChange = (val) => {
  console.log(`${val} items per page`);
};
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`);
};

const search = ref("");
const items = ref([]);
const searchKeyword = ref("");
const deleteDialogVisible = ref(false);
const deleteItem = ref(null); // 用于存储要删除的项
const editItem = ref(null); //
const totalItems = ref(0); // 用于存储总条数的响应式变量
const loading = ref(false);

const paginatedItems = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return items.value.slice(start, end);
});

const inputSearch = _.debounce(() => {
  if (searchKeyword.value.trim() !== "") {
    userSearch();
  } else {
    fetchData();
  }
}, 300); // 300ms的延迟

onMounted(() => {
  fetchData();
});

//获取用户数据
async function fetchData() {
  loading.value = true;
  try {
    const response = await axios.get("http://localhost:3000/api/users/userinfo");
    // 添加500ms延时
    await new Promise(resolve => setTimeout(resolve, 400));
    items.value = response.data;
    totalItems.value = response.data.length;
  } catch (error) {
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(error.response.data.message);
    }
  } finally {
    loading.value = false;
  }
}

//搜索用户数据
async function userSearch() {
  try {
    const response = await axios.get("http://localhost:3000/api/users/usersearch", {
      params: { keyword: searchKeyword.value },
    });
    items.value = response.data;
    totalItems.value = response.data.length; //
  } catch (error) {
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(error.response.data.message);
    }
  }
}

function clearSearch() {
  searchKeyword.value = "";
}

function reload() {
  location.reload();
}

const addDialogVisible = ref(false);
const editDialogVisible = ref(false);

const addFormData = ref({
  name: "",
  username: "",
  password: "",
  phone: "",
  role: "",
});

const editFormData = ref({
  name: "",
  username: "",
  password: "",
  phone: "",
  role: "",
});

function showAddDialog() {
  addDialogVisible.value = true;
}

//新增用户
async function submitAddForm() {
  // 校验字段是否为空
  // 定义必填字段及其错误提示
  const requiredFields = {
    name: "姓名不能为空",
    username: "用户名不能为空", 
    password: "密码不能为空",
    phone: "手机号不能为空",
    role: "角色不能为空"
  };
  // 检查必填字段
  for (const [field, message] of Object.entries(requiredFields)) {
    if (!addFormData.value[field]) {
      ElMessage.error(message);
      return;
    }
  }
  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(addFormData.value.phone)) {
    ElMessage.error("手机号格式不正确");
    return;
  }
  try {
    const response = await axios.post(
      "http://localhost:3000/api/users/useradd",
      addFormData.value,
    );
    if (response.data.message === "添加成功") {
      ElMessage.success("添加成功");
      addDialogVisible.value = false;
      fetchData();
    } else {
      ElMessage.error("添加失败");
    }
  } catch (error) {
    ElMessage.error(error.response.data.message);
  }
}

function showEditDialog(item) {
  editItem.value = item;
  editFormData.value = {
    name: item.name,
    username: item.username,
    phone: item.phone,
    role: item.role,
    // password: item.password
  };
  editDialogVisible.value = true;
}

//修改用户信息
async function submitEditForm() {
  try {
    if(!editFormData.value.password) {
      ElMessage.error("密码不能为空");
      return;
    }
    const response = await axios.put(
      `http://localhost:3000/api/users/useredit/${editItem.value.id}`,
      editFormData.value
    );
    if (response.data.message === "修改成功") {
      ElMessage.success("修改成功");
      editDialogVisible.value = false;
      // 重新获取数据
      fetchData();
    } else {
      ElMessage.error("修改失败");
    }
  } catch (error) {
    ElMessage.error(error.response.data.message);
  }
}

function showDeleteDialog(item) {
  // 假设 deleteItem 是用于存储要删除的项的响应式变量
  deleteItem.value = item;
  deleteDialogVisible.value = true;
}

// 删除用户信息
async function confirmDelete() {
  if (deleteItem.value) {
    try {
      const response = await axios.delete(
        `http://localhost:3000/api/users/userdelete/${deleteItem.value.id}`
      );
      if (response.data.message === "删除成功") {
        ElMessage.success("删除成功");
        fetchData();
        deleteDialogVisible.value = false;
      } else {
        ElMessage.error("删除失败");
      }
    } catch (error) {
      ElMessage.error(error.response.data.message);
    }
  }
}

const getTotalItems = async () => {
  try {
    const response = await axios.get("http://localhost:3000/api/users/usertotal");
    totalItems.value = response.data.total; // 假设响应数据中有一个名为 'total' 的字段
  } catch (error) {
    //console.error("获取数据总条数失败:", error);
  }
};

// 调用 getTotalItems 方法以获取数据的总数
getTotalItems();

// 使用 defineExpose 显式地暴露给模板的属性和方法
defineExpose({
  items,
  searchKeyword,
  fetchData,
  search,
  clearSearch,
  reload,
});
</script>

<style scoped>
.search-box {
  margin: 12px 4px 30px 0px;
  width: 40%;
}

.search {
  display: flex;
  padding: 0;
}

.search .el-button {
  margin-right: 10px;
  /* 添加按钮之间的间隔 */
}

.search .ml10 {
  /* margin-left: 10px; */
  /* 添加额外的左侧间距 */
}

.search .el-input {
  margin-right: 10px;
  /* 添加输入框与后面按钮之间的间隔 */
}

/* 确保最后一个按钮后面没有多余的间隔 */
.search .el-button:last-child {
  margin-right: 0;
}

.tar {
  margin: 0px 0px 0px 0px;
}

.tar .el-button {
  margin-left: 10px;
}

.demo-pagination-block {
  height: 90%;
}

.demonstration {
  height: 90%;
}

.el-table {
  height: 97.5%;
}

.el-table-column {
  height: 10rem;
}

.el-pagination {
  position: absolute;
  z-index: 100;
  bottom: 2rem;
  left: 47rem;
  background-color: whitesmoke;
  padding: 10px;
  border-radius: 25px;
}
</style>
